# 用户登录模块
from django.http import HttpResponseRedirect
from django.shortcuts import render
from smart_monitor.models import User


def is_sign_in(request):
    user_name = request.session.get("user_name", "un_sign_in")
    if user_name == "un_sign_in":
        return False, user_name
    else:
        return True, user_name


def sign_in(request):
    data_set = {"error_info": None}
    user_email = request.POST.get("inputEmail")
    user_pwd = request.POST.get("inputPassword")
    try:
        user = User.objects.get(user_email=user_email)
    except Exception as e:
        data_set["error_info"] = "邮箱不存在，请先注册"
        return render(request, "sign_in.html", data_set)

    # 登录成功
    if user.user_pwd == user_pwd:
        request.session["user_name"] = user.user_name
        request.session["user_id"] = user.id
        # 退出浏览器session失效
        request.session.set_expiry(0)
        return HttpResponseRedirect("/index")


class SignIn(object):
    def __init__(self, request):
        self.request = request

    def run(self):
        if self.request.method == "POST":
            return sign_in(self.request)
        return render(self.request, "sign_in.html", {"error_info": None})
